package com.vito.oa.email.util;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.search.AddressTerm;

public class OaFromTerm extends AddressTerm {

	private static final long serialVersionUID = 8657509581220497155L;

	protected OaFromTerm(Address address) {
		super(address);
	}

	@Override
	public boolean match(Message msg) {
		Address[] from;

		try {
			from = msg.getFrom();
		} catch (Exception e) {
			return false;
		}

		if (from == null){
			return false;
		}
		InternetAddress patterna = (InternetAddress) address;
		String pattern = patterna.getAddress();
		for (int i = 0; i < from.length; i++)
			if (fromMatch(from[i], pattern)) {
				return true;
			}
		return false;
	}
	
	private boolean fromMatch(Address a, String pattern) {
		if (a instanceof InternetAddress) {
			InternetAddress ia = (InternetAddress) a;
			if (ia.getAddress() != null) {
				return emailMatch(ia.getAddress(), pattern, true);
			}
			return false;
		} else
			return emailMatch(a.toString(), pattern, true);
	}
	
	private boolean emailMatch(String s, String pattern, boolean ignoreCase) {
		int len = s.length() - pattern.length();
		for (int i = 0; i <= len; i++) {
			if (s.regionMatches(ignoreCase, i, pattern, 0, pattern.length()))
				return true;
		}
		return false;
	}

}
